﻿using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;
using DTcms.Common;
using MintCyclingData;
using MintCyclingService.Common;
using MintCyclingService.LogServer;
using MintCyclingService.UserAccount;
using MintCyclingService.Utils;
using MintCyclingService.WeixinApliay;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Utility.Common;
using Utility.LogHelper;

namespace MintCyclingService.alipay
{
    public class AlipayTradeService : IAlipayTradeService
    {
        //获取配置文件中的值
        private static string AppID = System.Web.Configuration.WebConfigurationManager.AppSettings["AppID"];                      //APPID

        private static string App_private_Key = System.Web.Configuration.WebConfigurationManager.AppSettings["App_private_Key"];         //私钥
        private static string Alipay_public_Key = System.Web.Configuration.WebConfigurationManager.AppSettings["Alipay_public_Key"];     //公钥
        private static string Charset = System.Web.Configuration.WebConfigurationManager.AppSettings["Charset"];             //编码方式
        private static string SellerID = System.Web.Configuration.WebConfigurationManager.AppSettings["SellerID"];           //收款支付宝用户ID
        private static string ProductCode = System.Web.Configuration.WebConfigurationManager.AppSettings["ProductCode"];    //销售产品码，商家和支付宝签约的产品码
        private static string notify_url = System.Web.Configuration.WebConfigurationManager.AppSettings["notify_url"];      //获取服务器异步通知页面路径
        private static string YjAmoiunt = System.Web.Configuration.WebConfigurationManager.AppSettings["YjAmount"];   //押金

        //支付宝通知验证路径
        private string Https_veryfy_url = "https://mapi.alipay.com/gateway.do?service=notify_verify&";

        private IUserAccountService _UserAccountService = new UserAccountService();
        private IWeixinAlipayTradeService _WeixinService = new WeixinAlipayTradeService();

        private ILogService LogServer = new LogService();
        #region 生成APP支付订单信息及签名

        /// <summary>
        /// 生成APP支付订单信息
        /// 主要用来做签名用的
        /// </summary>
        /// <returns></returns>
        public ResultModel GetAlipayTradeAppPay(AlipayTradeModel para)
        {
            //测试押金短信
            //Guid userGuid = new Guid();
            //string T = "押金";
            //int aa = 11;
            //string remark = "【薄荷单车】您支付宝" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日" + "收到充值押金RMB\"" + aa + "\",请及时查看。";
            //bool flg = _UserAccountService.UsersSendSMS(userGuid, "YJ201703271713140000000004", T, remark);

            var result = new ResultModel();
            string OrderNumber = string.Empty;
            string typeName = "RechargeBalanceOrDeposit";

            //对支付宝Url编码string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));进行解密
            //string encodedValue = HttpUtility.UrlDecode("app_id=2017030806107198&biz_content=%7b%22body%22%3a%22%e7%94%a8%e6%88%b7%e5%85%85%e5%80%bc%e9%92%b1%e5%8c%85%22%2c%22out_trade_no%22%3a%22YE201703230953530000000001%22%2c%22product_code%22%3a%22QUICK_MSECURITY_PAY%22%2c%22subject%22%3a%22%e7%94%a8%e6%88%b7%e5%85%85%e5%80%bc%22%2c%22total_amount%22%3a%22200%22%7d&charset=utf-8&format=json&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2017-03-23+09%3a54%3a13&version=1.0&sign=VUTpywXcQMm1PgGnMJPrOjBs%2fDlVAU%2fPKBfn1ODXypMC7nCc6W917%2f5KzfYd89ftQwpSH9C7vrCZra5H8Ns691Pj4EtkfAnllYVz1EAlWh2mmhe7IOUp1RGQwXyfY1d0vY4cZOEcxB9vFXGU%2f1wuS2xpQeUgup6BDtR2h9I%2bv3nffwQYOpoj8FjreyuF4vwT0orNOnV4cXGZwjLzH2wlgdct1SEFuDXtd9C1A1yb32GdsKtsvIvr1x1p0awEn2F8foe51SmsxuiELoUZxAU%2bN463tMW%2brz3b3ZrrRxwJBAZ97zrBZum%2bo%2fmm3dYJ5e6abLWYziTRtL8nE6XMSwwRAA%3d%3d", Encoding.GetEncoding(Charset));
            try
            {
                if (para == null)
                {
                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 0, para.TotalAmount, "请求参数出现问题！");

                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.ParaModelNotExist, Message = ResPrompt.ParaModelNotExistMessage };
                }
                //生成唯一的订单号
                if (para.TypeName == 1) //押金充值
                {
                    OrderNumber = "YJ" + OrderHelper.GenerateOrderNumber();
                }
                else //余额充值
                {
                    OrderNumber = "YE" + OrderHelper.GenerateOrderNumber();
                }

                IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppID, App_private_Key, "json", "1.0", "RSA2", Alipay_public_Key, Charset, false);
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如：alipay.trade.app.pay

                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.Body = para.Body;
                model.Subject = para.Subject;
                model.TotalAmount = para.TotalAmount;
                model.ProductCode = ProductCode;
                model.OutTradeNo = OrderNumber;       //订单号
                model.TimeoutExpress = "30m";         //默认1小时
                model.SellerId = SellerID;
                request.SetBizModel(model);
                request.SetNotifyUrl(notify_url);   //异步通知路径-商户外网可以访问的异步地址
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = client.SdkExecute(request);

                //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
                //System.Web.HttpContext.Current.Response.Write(System.Web.HttpUtility.HtmlEncode(response.Body));
                //页面输出的response.Body就是orderString 可以直接给客户端请求，无需再做处理.注：只适用于pc
                if (!string.IsNullOrEmpty(response.Body))
                {
                    #region 生成订单信息：分别为用户充值钱包余额和充值押金

                    decimal amount = decimal.Parse(para.TotalAmount);
                    if (para.TypeName == 1) //表示押金充值业务处理
                    {
                        using (var db = new MintBicycleDataContext())
                        {
                            #region 押金充值基本信息表和添加押金充值记录表(订单表)

                            try
                            {
                                //var userDeposit = (from d in db.Deposit
                                //                   join u in db.UserDepositRechargeRecord on d.UserInfoGuid equals u.UserInfoGuid
                                //                   where (d.Amount!=0) && u.Status==1 && d.UserInfoGuid==para.UserInfoGuid
                                //                   select d);
                                //判断用户是否已充值押金
                                var queryD = db.Deposit.FirstOrDefault(x => x.UserInfoGuid == para.UserInfoGuid && (x.Amount != 0 || x.Amount == decimal.Parse(YjAmoiunt)));
                                if (queryD != null) //表示已充值押金
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 0, para.TotalAmount, "用户已充值押金，不能重复充值！");
                                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayExistErrorCode, Message = ResPrompt.AlipayExistErrorMessageMessage };
                                }

                                var query = db.Deposit.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                                if (query == null)
                                {
                                    var Deposit = new Deposit();
                                    Deposit.DepositGuid = Guid.NewGuid();
                                    Deposit.Amount = 0;
                                    Deposit.UserInfoGuid = para.UserInfoGuid;
                                    Deposit.CreateBy = para.UserInfoGuid;
                                    Deposit.CreateTime = DateTime.Now;
                                    Deposit.IsDeleted = false;
                                    db.Deposit.InsertOnSubmit(Deposit);
                                    db.SubmitChanges();
                                }
                                else if (query != null && ((query.Amount == 0))) //修改
                                {
                                    query.Amount = 0;
                                    query.IsDeleted = false;
                                    query.UpdateBy = para.UserInfoGuid;
                                    query.UpdateTime = DateTime.Now;
                                    db.SubmitChanges();
                                }
                                else //此用户已充值了押金不能重复充值
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 0, para.TotalAmount, "用户充值押金出现异常！");
                                    LogHelper.Error("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + "");
                                    //FileLog.Log("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + "", typeName);
                                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayExistErrorCode, Message = ResPrompt.AlipayExistErrorMessageMessage };
                                }

                                //充值押金记录信息
                                var UserDeposit = new UserDepositRechargeRecord();
                                UserDeposit.UserDepositRechargeGuid = Guid.NewGuid();
                                UserDeposit.UserInfoGuid = para.UserInfoGuid;
                                UserDeposit.Amount = amount;
                                UserDeposit.RechargeType = "支付宝";
                                UserDeposit.MoneyType = "1";                        //1表示充值
                                UserDeposit.Status = 2;                             //2交易创建，等待买家付款
                                UserDeposit.PayDate = DateTime.Now;
                                UserDeposit.OutTradeNo = OrderNumber;              //订单号码
                                UserDeposit.Trade_no = null;                       //支付宝交易号
                                UserDeposit.Sign_type = null;                     // 签名类型RSA2
                                UserDeposit.Sign = null;                          // 签名
                                UserDeposit.Remark = " 用户Guid为" + para.UserInfoGuid + ",充值押金为：" + amount + "元。";
                                UserDeposit.CreateBy = para.UserInfoGuid;
                                UserDeposit.CreateTime = DateTime.Now;
                                UserDeposit.IsDeleted = false;

                                db.UserDepositRechargeRecord.InsertOnSubmit(UserDeposit);
                                db.SubmitChanges();
                            }
                            catch (Exception ex)
                            {
                                LogServer.InsertDBPay(para.UserInfoGuid, 0, 0, para.TotalAmount, "用户充值押金出现异常！");
                                LogHelper.Error("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成押金充值订单信息异常!",ex);
                                //FileLog.Log("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成押金充值订单信息异常!", typeName);
                                return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayDepositOrderErrorCode, Message = ResPrompt.AlipayDepositOrderErrorMessageMessage };
                            }

                            #endregion 押金充值基本信息表和添加押金充值记录表(订单表)
                        }
                    }
                    else //表示钱包余额业务处理
                    {
                        using (var db = new MintBicycleDataContext())
                        {
                            #region 充值账户信息表和添加用户充值余额记录表(订单表)

                            try
                            {
                                var query = db.AccountInfo.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                                if (query == null)
                                {
                                    var Account = new AccountInfo();
                                    Account.AccountGuid = Guid.NewGuid();
                                    Account.UserInfoGuid = para.UserInfoGuid;
                                    Account.BalanceAmount = 0;
                                    Account.UsableAmount = 0;
                                    Account.CreateTime = DateTime.Now;
                                    Account.CreateBy = para.UserInfoGuid;
                                    Account.IsDeleted = false;
                                    db.AccountInfo.InsertOnSubmit(Account);
                                    db.SubmitChanges();
                                }

                                //充值钱包金额记录表
                                var UserRechargeRecord = new UserRechargeRecord();
                                UserRechargeRecord.UserRechargeGuid = Guid.NewGuid();
                                UserRechargeRecord.UserInfoGuid = para.UserInfoGuid;
                                UserRechargeRecord.Amount = amount;
                                //充值的方式：1支付宝；2微信
                                UserRechargeRecord.RechargeType = "支付宝";
                                //充值的状态：0充值失败；1充值成功
                                UserRechargeRecord.Status = 2;                        //2交易创建，等待买家付款
                                UserRechargeRecord.PayDate = DateTime.Now;
                                UserRechargeRecord.OutTradeNo = OrderNumber;       //商户唯一订单号码
                                UserRechargeRecord.Trade_no = null;                  //支付宝交易号
                                UserRechargeRecord.Sign_type = null;                 // 签名类型RSA2
                                UserRechargeRecord.Sign = null;                      // 签名
                                UserRechargeRecord.Remark = " 用户Guid为" + para.UserInfoGuid + ",充值钱包余额为：" + amount + "元。";
                                UserRechargeRecord.CreateBy = para.UserInfoGuid;
                                UserRechargeRecord.CreateTime = DateTime.Now;
                                UserRechargeRecord.IsDeleted = false;

                                db.UserRechargeRecord.InsertOnSubmit(UserRechargeRecord);
                                db.SubmitChanges();
                            }
                            catch (Exception ex)
                            {
                                LogServer.InsertDBPay(para.UserInfoGuid, 0, 1, para.TotalAmount, "用户充值余额出现异常！");
                                //FileLog.Log("用户充值余额异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成账户余额充值订单信息异常!", typeName);
                                LogHelper.Error("用户充值余额异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成账户余额充值订单信息异常!", ex);
                                return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayAccountOrderErrorCode, Message = ResPrompt.AlipayAccountOrdeErrorMessageMessage };
                            }

                            #endregion 充值账户信息表和添加用户充值余额记录表(订单表)
                        }
                    }
                    result.IsSuccess = true;
                    result.MsgCode = "0";
                    result.Message = "生成APP支付订单信息成功！";
                    //result.ResObject = HttpUtility.HtmlEncode(response.Body);
                    //result.ResObject = response.Body+ "&notify_url="+notify_url;
                    result.ResObject = response.Body;
                    //日志记录
                    //FileLog.Log("用户充值账户余额成功信息：当前用户Guid为" + para.UserInfoGuid + ",充值时间："+DateTime.Now+",充值了余额为：" + para.TotalAmount + "元,生成的订单信息是:" + response.Body, typeName);

                    #endregion 生成订单信息：分别为用户充值钱包余额和充值押金
                }
                else
                {
                    LogServer.InsertDBPay(para.UserInfoGuid, 0,1, para.TotalAmount, "生成APP支付订单信息失败！");
                    result.IsSuccess = false;
                    result.MsgCode = "1";
                    result.Message = "生成APP支付订单信息失败！";
                    result.ResObject = null;
                    //日志记录
                    LogHelper.Error("用户充值账户余额失败信息：当前用户Guid为" + para.UserInfoGuid + ",充值时间：" + DateTime.Now + ",充值了余额为：" + para.TotalAmount + "元,生成的订单信息是:" + response.Body);
                    //FileLog.Log("用户充值账户余额失败信息：当前用户Guid为" + para.UserInfoGuid + ",充值时间：" + DateTime.Now + ",充值了余额为：" + para.TotalAmount + "元,生成的订单信息是:" + response.Body, typeName);
                }
            }
            catch (Exception ex)
            {
                LogServer.InsertDBPay(para.UserInfoGuid, 0, 3, para.TotalAmount, "用户充值押金或余额，服务器生成订单异常");
                LogHelper.Error("用户充值异常信息：当前用户Guid为" + para.UserInfoGuid + ",服务器生成订单信息异常!", ex);
                //FileLog.Log("用户充值异常信息：当前用户Guid为" + para.UserInfoGuid + ",服务器生成订单信息异常!", typeName);
                return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayServiceErrorCode, Message = ResPrompt.AlipayServiceErrorMessageMessage };
            }
            return result;
        }

        #endregion 生成APP支付订单信息及签名



 
        #region 集成支付宝退押金接口

        /// <summary>
        /// 用户交易退款接口
        /// 当交易发生之后一段时间内，由于买家或者卖家的原因需要退款时，卖家可以通过退款接口将支付款退还给买家，支付宝将在收到退款请求并且验证成功之后，按照退款规则将支付款按原路退到买家帐号上。 交易超过约定时间（签约时设置的可退款时间）的订单无法进行退款 支付宝退款支持单笔交易分多次退款，多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。一笔退款失败后重新提交，要采用原来的退款单号。总退款金额不能超过用户实际支付金额
        /// </summary>
        /// <param name="para">用户Guid</param>
        /// <returns></returns>
        public ResultModel AlipayTradeRefund(UserDepositRefundModel para)
        {
            string typeName = "UserRefundDeposit";
            IUserAccountService userService = new UserAccountService();
            var result = new ResultModel();
            AlipayTradeRefundModel userRefund = new AlipayTradeRefundModel();

            using (var db = new MintBicycleDataContext())
            {
                //新增判断
                var QueryRe = db.Reservation.OrderByDescending(r => r.CreateTime).FirstOrDefault(r => r.UserInfoGuid == para.UserInfoGuid && r.Status == 1);
                if (QueryRe != null)
                {
                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2,"押金", "您在预约用车中，不能退押金！");
                    return new ResultModel { IsSuccess = false, MsgCode = "0", Message = "您在预约用车中，不能退押金！" };
                }

                    var DepositQueryLog = db.UserDepositRechargeRecord.OrderByDescending(s=>s.CreateTime).FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid && s.Status==1 && s.MoneyType=="1");
                if (DepositQueryLog != null)
                {
                    if (DepositQueryLog.RechargeType == "支付宝")
                    {
                        //FileLog.Log("1\r\n", "RefundLog");
                        #region 支付宝退押金

                        try
                        {
                            var RefundQuery = db.Deposit.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                            if (RefundQuery != null && RefundQuery.Amount == 0)
                            {
                                LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "您的押金已退，不能重复退押金！");
                                return new ResultModel { IsSuccess = false, MsgCode = "0", Message = "您的押金已退，不能重复退押金！" };
                            }

                            //查询用户最新的一条充值押金记录信息
                            var query = (from d in db.UserDepositRechargeRecord
                                         where d.UserInfoGuid == para.UserInfoGuid && d.MoneyType == "1" && d.Status == 1 && d.RechargeType == "支付宝"
                                         orderby d.CreateTime descending
                                         select d).FirstOrDefault();
                            if (query != null)
                            {
                                userRefund.trade_no = query.Trade_no;                                 //支付宝交易号
                                userRefund.out_trade_no = query.OutTradeNo;                          //商户订单号
                                userRefund.refund_amount = decimal.Parse(query.Amount.ToString());  //退款的金额

                                ////测试模拟数据
                                //userRefund.trade_no = "2017032521001004090239260132";                            //支付宝交易号
                                //userRefund.out_trade_no = "YE201703251751120000000002";                         //商户订单号
                                //userRefund.refund_amount = decimal.Parse("0.01");  //退款的金额

                                #region 处理业务

                                //调用支付宝退款接口协议
                                IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppID, App_private_Key, "json", "1.0", "RSA2", Alipay_public_Key, Charset, false);
                                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                                request.BizContent = "{" +
                                 "   \"out_trade_no\":\"" + userRefund.out_trade_no + "\"," +
                                 "    \"trade_no\":\"" + userRefund.trade_no + "\"," +
                                 "    \"refund_amount\":" + userRefund.refund_amount + "," +
                                 "    \"refund_reason\":\"正常退款\"" +
                                "}";
                                AlipayTradeRefundResponse response = client.Execute(request);
                                JObject jo = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(response.Body);
                                string Status = jo["alipay_trade_refund_response"]["code"].ToString();

                                if (Status == "10000" && response.Body != null)
                                {
                                    //退款支付时间
                                    string gmt_refund_pay = jo["alipay_trade_refund_response"]["gmt_refund_pay"].ToString();
                                    //支付宝交易号
                                    string trade_no = jo["alipay_trade_refund_response"]["trade_no"].ToString();
                                    //商户订单号
                                    string out_trade_no = jo["alipay_trade_refund_response"]["out_trade_no"].ToString();
                                    //退款总金额
                                    decimal refund_fee = decimal.Parse(jo["alipay_trade_refund_response"]["refund_fee"].ToString());
                                    //签名
                                    string sign = jo["sign"].ToString();

                                    //修改押金表
                                    var queryD = db.Deposit.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                                    if (queryD != null)
                                    {
                                        queryD.Amount = 0;
                                        queryD.UpdateBy = para.UserInfoGuid;
                                        queryD.UpdateTime = DateTime.Now;
                                        //queryD.IsDeleted = true;
                                        db.SubmitChanges();
                                    }
                                    //添加退押金记录表
                                    var UserDepositRecharge = new UserDepositRechargeRecord();
                                    UserDepositRecharge.UserDepositRechargeGuid = Guid.NewGuid();
                                    UserDepositRecharge.UserInfoGuid = para.UserInfoGuid;
                                    UserDepositRecharge.Amount = refund_fee;
                                    //退款的方式：1支付宝；2微信
                                    UserDepositRecharge.RechargeType = "支付宝";
                                    UserDepositRecharge.MoneyType = "2";   //MoneType=2表示退押金
                                                                           //退款的状态：0退款失败；1退款成功
                                    UserDepositRecharge.Status = 1;
                                    UserDepositRecharge.PayDate = DateTime.Parse(gmt_refund_pay);     //退款时间
                                    UserDepositRecharge.OutTradeNo = out_trade_no;                   //订单号码
                                    UserDepositRecharge.Trade_no = trade_no;                        //支付宝交易号
                                    UserDepositRecharge.Sign_type = "RSA2";                        // 签名类型RSA2
                                    UserDepositRecharge.Sign = sign;                              // 签名
                                    UserDepositRecharge.Remark = " 用户Guid为" + para.UserInfoGuid + "退押金了99元。";
                                    UserDepositRecharge.CreateBy = para.UserInfoGuid;
                                    UserDepositRecharge.CreateTime = DateTime.Now;
                                    UserDepositRecharge.IsDeleted = false;

                                    db.UserDepositRechargeRecord.InsertOnSubmit(UserDepositRecharge);
                                    db.SubmitChanges();

                                    //发送短信消息通知用户
                                    string T = string.Empty;
                                    string OutTradeNo = string.Empty;

                                    string remark = "【薄荷单车】您支付宝" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日" + "收到退款\"" + refund_fee + "\"元,请及时查看。";
                                    bool flg = userService.UsersSendSMS(para.UserInfoGuid, OutTradeNo, T, remark);

                                    result.IsSuccess = true;
                                    result.MsgCode = "0";
                                    result.Message = "退押金成功！";
                                    result.ResObject = null;
                                }
                                else if (Status == "20000")
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "服务不可用！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "20000";
                                    result.Message = "服务不可用！";
                                    result.ResObject = null;
                                }
                                else if (Status == "40001")
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "缺少必选参数！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "40001";
                                    result.Message = "缺少必选参数！";
                                    result.ResObject = null;
                                }
                                else if (Status == "40002")
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "非法参数！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "40002";
                                    result.Message = "非法的参数！";
                                    result.ResObject = null;
                                }
                                else if (Status == "40004")
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "业务处理失败！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "40004";
                                    result.Message = "业务处理失败！";
                                    result.ResObject = null;
                                }
                                else if (Status == "40006")
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "权限不足！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "40006";
                                    result.Message = "权限不足！";
                                    result.ResObject = null;
                                }
                                else
                                {
                                    LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "退押金失败！");
                                    result.IsSuccess = false;
                                    result.MsgCode = "0";
                                    result.Message = "退押金失败！";
                                    result.ResObject = null;
                                }

                                #endregion 处理业务

                                //日志记录
                                // FileLog.Log("用户退押金信息：订单号为" + userRefund.out_trade_no + ",支付宝交易号："+ userRefund .trade_no+ "," + "退款金额为：" + userRefund.refund_amount + "退押金支付宝返回Json信息是:" + response.Body, typeName);
                            }
                            else
                            {
                                LogServer.InsertDBPay(para.UserInfoGuid, 0, 2, RefundQuery.Amount.ToString(), "没此用户的最新充值记录，退押金失败！");
                                LogHelper.Error("没用此用户的最新充值记录，退押金失败，此用户Guid:" + para.UserInfoGuid+"");
                                //FileLog.Log("没用此用户的最新充值记录，退押金失败，此用户Guid:" + para.UserInfoGuid, typeName);
                                return new ResultModel { IsSuccess = false, MsgCode = "0", Message = "退押金失败" };
                            }
                        }
                        catch (Exception ex)
                        {
                            LogServer.InsertDBPay(para.UserInfoGuid, 0, 2,"押金", "退押金出现异常！");
                            //FileLog.Log("退押金异常，" + ex.Message, typeName);
                            LogHelper.Error("退押金异常:"+ex.Message,ex);
                            return new ResultModel { IsSuccess = false, MsgCode = "1103", Message = "退押金异常" + ex.Message };
                        }

                        #endregion 支付宝退押金
                        //FileLog.Log("2\r\n", "RefundLog");
                    }
                    else
                    {
                        //调用微信退押金接口
                        _WeixinService.WeixinRefund(para);
                       //FileLog.Log("100\r\n", "WeiXinRefundLog");

                    }
                }
            }
            return result;
        }

        #endregion 集成支付宝退押金接口



        #region 支付宝异步回调验证签名和验证消息是否是支付宝发出的 暂时废弃

        /// <summary>
        /// 支付宝异步回调验证签名
        /// </summary>
        public void GetRSACheckV1()
        {
            var result = new ResultModel();

            #region 说明

            //验签（解决问题成功率90 %） issig为false，一般有几种可能：
            //1、支付宝公鈅（特别是PHP编程语言，一定要用demo中的支付宝公钥文件）或者key有问题；
            //2、参与验签的待签名字符串存在中文乱码，或者多了商户的自定义参数（异步通知地址带自定义参数；），或者少了一些异步通知参数；
            //3、需要RSA验签，但是商户用MD5验签；
            //4、验签的编码格式有问题（主要是java和c#）；
            //5、验签的代码逻辑有问题，强烈建议参考demo的
            //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
            //bool RSACheckV1(IDictionary<string, string> parameters, string alipaypublicKey, string charset, string signType, bool keyFromFile)
            //如果你用的demo里的支付宝公钥是写在Config.cs文件里而不是从文件里读取的话，用Boolean signVerified = AlipaySignature.RSACheckV1()进行验签时，公钥的变量需要加上"-----BEGIN PUBLIC KEY-----\r\n" + Config.alipay_public_key + "-----END PUBLIC KEY-----\r\n\r\n"

            #endregion 说明

            #region 验证签名和验证是否是支付宝发来的通知

            //获取所有异步通知参数
            IDictionary<string, string> dic = GetRequestPost();
            if (dic.Count > 0)  //判断是否有带返回参数
            {
                try
                {
                    //验证签名调用
                    bool flag = AlipaySignature.RSACheckV1(dic, Alipay_public_Key, Charset, "RSA2", false);
                    bool verifyResult = Verify(dic, DTRequest.GetString("notify_id"), DTRequest.GetString("sign"));

                    #region 处理订单的业务逻辑

                    if (flag && verifyResult) //验签通过并且同时验证是否是支付宝发来的通知同时成立--验证签名及notify_id合法性校验都是true的判断逻辑里
                    {
                        string trade_no = DTRequest.GetString("trade_no");                      //支付宝交易号
                        string out_trade_no = DTRequest.GetString("out_trade_no").ToUpper();     //获取订单号
                        string total_amount = DTRequest.GetString("total_amount");             //获取总金额
                        string trade_status = DTRequest.GetString("trade_status");          //交易状态

                        //int tradeStatus = GetTradeStatus(trade_status); //交易状态

                        if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS")
                        {
                            //处理订单的业务逻辑
                            if (out_trade_no.StartsWith("YE")) //余额充值
                            {
                                #region 处理余额相关业务逻辑

                                using (var db = new MintBicycleDataContext())
                                {
                                    var UserRecharge = db.UserRechargeRecord.FirstOrDefault(s => s.OutTradeNo == out_trade_no);
                                    if (UserRecharge == null)
                                    {
                                        System.Web.HttpContext.Current.Response.Write("该订单号不存在");
                                        return;
                                    }
                                    if (UserRecharge.Amount != decimal.Parse(total_amount))
                                    {
                                        System.Web.HttpContext.Current.Response.Write("订单金额和支付金额不相符");
                                        return;
                                    }
                                    if (UserRecharge.Status == 1) //已付款
                                    {
                                        System.Web.HttpContext.Current.Response.Write("success");
                                        return;
                                    }

                                    //修改订单状态
                                    var UserReQuery = db.UserRechargeRecord.FirstOrDefault(s => s.OutTradeNo == out_trade_no);
                                    if (UserReQuery != null)
                                    {
                                        UserReQuery.Status = 1;
                                        //UserReQuery.Amount = decimal.Parse(total_amount);
                                        UserReQuery.PayDate = DateTime.Parse(DTRequest.GetString("gmt_payment"));
                                        //UserReQuery.Out_trade_no = out_trade_no;
                                        UserReQuery.Trade_no = trade_no;
                                        UserReQuery.Sign = DTRequest.GetString("Sign"); ;
                                        UserReQuery.Sign_type = DTRequest.GetString("Sign_type");
                                        UserReQuery.UpdateTime = DateTime.Now;
                                        db.SubmitChanges();

                                        //账户信息
                                        var QueryAccount = db.AccountInfo.FirstOrDefault(s => s.UserInfoGuid == UserReQuery.UserInfoGuid);
                                        if (QueryAccount != null)
                                        {
                                            QueryAccount.BalanceAmount += decimal.Parse(total_amount);
                                            QueryAccount.UsableAmount += decimal.Parse(total_amount);
                                            QueryAccount.UpdateBy = UserReQuery.UserInfoGuid;
                                            QueryAccount.UpdateTime = DateTime.Now;
                                            db.SubmitChanges();
                                        }
                                    }
                                }

                                #endregion 处理余额相关业务逻辑
                            }
                            else //押金充值
                            {
                                #region 处理押金相关业务逻辑

                                using (var db = new MintBicycleDataContext())
                                {
                                    var UserDeposit = db.UserDepositRechargeRecord.FirstOrDefault(s => s.OutTradeNo == out_trade_no);
                                    if (UserDeposit == null)
                                    {
                                        System.Web.HttpContext.Current.Response.Write("该订单号不存在");
                                        return;
                                    }
                                    if (UserDeposit.Amount != decimal.Parse(total_amount))
                                    {
                                        System.Web.HttpContext.Current.Response.Write("订单金额和支付金额不相符");
                                        return;
                                    }
                                    if (UserDeposit.Status == 1) //已付款
                                    {
                                        System.Web.HttpContext.Current.Response.Write("success");
                                        return;
                                    }

                                    //修改订单状态
                                    var UserReQuery = db.UserDepositRechargeRecord.FirstOrDefault(s => s.OutTradeNo == out_trade_no);
                                    if (UserReQuery != null)
                                    {
                                        UserReQuery.Status = 1;  //成功
                                        //UserReQuery.Amount = decimal.Parse(total_amount);
                                        UserReQuery.PayDate = DateTime.Parse(DTRequest.GetString("gmt_payment"));
                                        //UserReQuery.Out_trade_no = out_trade_no;
                                        UserReQuery.Trade_no = trade_no;
                                        UserReQuery.Sign = DTRequest.GetString("Sign"); ;
                                        UserReQuery.Sign_type = DTRequest.GetString("Sign_type");
                                        UserReQuery.UpdateTime = DateTime.Now;
                                        db.SubmitChanges();

                                        //押金信息
                                        var query = db.Deposit.FirstOrDefault(s => s.UserInfoGuid == UserReQuery.UserInfoGuid);
                                        if (query != null)
                                        {
                                            query.Amount = decimal.Parse(total_amount);
                                            query.IsDeleted = false;
                                            query.UpdateBy = UserReQuery.UserInfoGuid;
                                            query.UpdateTime = DateTime.Now;
                                            db.SubmitChanges();
                                        }
                                    }
                                }

                                #endregion 处理押金相关业务逻辑

                            }
                        }
                        else if (trade_status == "TRADE_CLOSED") //交易关闭
                        {
                            System.Web.HttpContext.Current.Response.Write("TRADE_CLOSED");
                        }
                        else //充值失败
                        {
                            System.Web.HttpContext.Current.Response.Write("failure");
                        }
                        System.Web.HttpContext.Current.Response.Write("success");  //充值成功
                        return;
                    }
                    else //支付宝验签失败，请检查对应的接口调用
                    {
                        System.Web.HttpContext.Current.Response.Write("failure");
                    }

                    #endregion 处理订单的业务逻辑
                }
                catch (Exception ex)
                {
                    System.Web.HttpContext.Current.Response.Write("failure");
                }

                #endregion 验证签名和验证是否是支付宝发来的通知

            }
        }

        /// <summary>
        ///  验证消息是否是支付宝发出的合法消息
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="notify_id">通知验证ID</param>
        /// <param name="sign">支付宝生成的签名结果</param>
        /// <returns>验证结果</returns>
        public bool Verify(IDictionary<string, string> inputPara, string notify_id, string sign)
        {
            //获取返回回来的待签名数组签名后结果
            //string mysign = GetResponseMysign(inputPara);
            //获取是否是支付宝服务器发来的请求的验证结果
            string responseTxt = "true";
            if (notify_id != "")
            {
                responseTxt = GetResponseTxt(notify_id);
            }

            //写日志记录（若要调试，请取消下面两行注释）
            //string sWord = "responseTxt=" + responseTxt + "\n sign=" + sign + "&mysign=" + mysign + "\n 返回回来的参数：" + GetPreSignStr(inputPara) + "\n ";
            //Core.LogResult(sWord);

            //验证
            //responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
            //mysign与sign不等，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
            if (responseTxt == "true")//验证成功
            {
                return true;
            }
            else//验证失败
            {
                return false;
            }
        }

        /// <summary>
        /// 获取是否是支付宝服务器发来的请求的验证结果
        /// </summary>
        /// <param name="notify_id">通知验证ID</param>
        /// <returns>验证结果</returns>
        private string GetResponseTxt(string notify_id)
        {
            string veryfy_url = Https_veryfy_url + "partner=" + SellerID + "&notify_id=" + notify_id;

            //获取远程服务器ATN结果，验证是否是支付宝服务器发来的请求
            string responseTxt = Get_Http(veryfy_url, 120000);  //2分钟120秒

            return responseTxt;
        }

        /// <summary>
        /// 获取远程服务器ATN结果
        /// </summary>
        /// <param name="strUrl">指定URL路径地址</param>
        /// <param name="timeout">超时时间设置</param>
        /// <returns>服务器ATN结果</returns>
        private string Get_Http(string strUrl, int timeout)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }
                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "错误：" + exp.Message;
            }
            return strResult;
        }

        /// 获取支付宝主动发送POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// request回来的信息组成的数组
        public static IDictionary<string, string> GetRequestPost()
        {
            int i = 0;
            //创建泛型哈希表，然后加入元素
            IDictionary<string, string> sArray = new Dictionary<string, string>(); //将异步通知中收到的待验证所有参数都存放到IDictionary中
            NameValueCollection coll;
            //表单变量加载到NameValueCollection变量
            coll = System.Web.HttpContext.Current.Request.Form;

            //得到所有形式的名字添加到一个字符串数组
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], System.Web.HttpContext.Current.Request.Form[requestItem[i]]);
            }

            return sArray;
        }

        /// <summary>
        /// 交易状态说明
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public static int GetTradeStatus(string T)
        {
            //充值的状态：0充值失败()；1充值成功--TRADE_SUCCESS；2交易创建，等待买家付款--WAIT_BUYER_PAY；3.未付款交易超时关闭，或支付完成后全额退款--TRADE_CLOSED；4.交易结束，不可退款--TRADE_FINISHED
            int str = 0;
            switch (T)
            {
                case "TRADE_SUCCESS":
                    str = 1;
                    break;

                case "WAIT_BUYER_PAY":
                    str = 2;
                    break;

                case "TRADE_CLOSED":
                    str = 3;
                    break;

                case "TRADE_FINISHED":
                    str = 4;
                    break;

                default:
                    str = 0;
                    break;
            }
            return str;
        }

        #endregion 支付宝异步回调验证签名和验证消息是否是支付宝发出的 暂时废弃

    }
}